import Layout from '@/layout'
import Frame from '@/layout/TheFrame'
import Shim from '@/layout/TheShim'
import { constantRoutes } from '@/router'
import conf from '@/config'
import { setStore } from '@/utils/store'

function filterAsyncRoutes(routes) {
  if (!Array.isArray(routes)) { return routes }

  const accessedRoutes = routes.filter(route => {
    let component = route.component
    if (component) {
      if (component.slice(0, 1) === '/') {
        component = component.slice(1)
      }

      if (component === 'Layout') {
        route.component = Layout
      } else if (component === 'Frame') {
        route.component = Frame
      } else if (component === 'Shim') {
        route.component = Shim
      } else {
        console.error('当前环境', process.env.NODE_ENV)
        route.component = process.env.NODE_ENV === 'production'
          ? () => import('@/views/' + component + '.vue')
          : require('@/views/' + component + '.vue').default
      }
    }

    if (route.children && route.children.length) {
      route.children = filterAsyncRoutes(route.children)
    }

    return true
  })

  return accessedRoutes
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES(state, routes) {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }, data) {
    return new Promise(resolve => {
      setStore(conf.key.route, data)
      const accessedRoutes = filterAsyncRoutes(data).concat([{ path: '*', redirect: '/404', hidden: true }])
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
